﻿using SCG.WinForms;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;

namespace SCG.TurboSprite
{
    public class RotatedBitmapSprite : BitmapSprite
    {
        //constructor
        public RotatedBitmapSprite(Bitmap bmp, int numFrames)
            : base(bmp)
        {
            _degreesPerFrame = 360.0 / (double)numFrames;

            //see if we already created frames for this bitmap
            List<Bitmap> frames;
            if (_masterList.ContainsKey(bmp))
                frames = _masterList[bmp];
            else
            {
                frames = new List<Bitmap>();
                double rotation = 0;
                while (rotation < 360.0)
                {
                    Bitmap rotated = (Bitmap)ImageUtils.RotateImage(bmp, (float)rotation);
                    frames.Add(rotated);
                    rotation += _degreesPerFrame;
                }
                _masterList[bmp] = frames;
            }
            _myFrames = frames;
        }

        //select appropriate frame for each render
        public override void Process()
        {
            base.Process();
            int idx = 0;
            double rotation = 0;
            while (rotation <= FacingAngle)
            {
                idx++;
                rotation += _degreesPerFrame;
            }
            if (idx >= _myFrames.Count)
                idx = 0;
            try
            {
                Bitmap = _myFrames[idx];
            }
            catch
            {
            }
        }

        //static and private
        private double _degreesPerFrame;
        private List<Bitmap> _myFrames;
        private static Dictionary<Bitmap, List<Bitmap>> _masterList = new Dictionary<Bitmap, List<Bitmap>>();
    }
}
